const mongodb = require("mongodb");
const mongoClient = mongodb.MongoClient;

// 连接数据库
function _connect() {
    return new Promise((resolve, reject) => {
        mongoClient.connect("mongodb://127.0.0.1:27017", {useUnifiedTopology: true}, (err, client) => {
            if (err)
                reject("连接数据库失败")
            else
                resolve(client.db("ele"));
        })
    })
}
module.exports = {
    // 插入一条
    async insertOne(collName, insertObj) {
        const db = await _connect();
        return new Promise((resolve, reject) => {
            db.collection(collName).insertOne(insertObj, (err, results) => {
                if (err) reject("插入失败");
                else resolve("插入成功")
            })
        })
    },
    // 查找一条
    async findOne(collName, whereObj) {
        const db = await _connect();// 获得你要操作的数据库
        return new Promise((resolve, reject) => {
            db.collection(collName).findOne(whereObj, (err, result) => {
                if (err)
                    reject("查找失败")
                else
                    resolve(result);
            })
        })

    },
    // 更新一条信息
    async updateOne(collName, whereObj, upObj) {
        const db = await _connect();
        return new Promise((resolve, reject) => {
            db.collection(collName).updateOne(whereObj, upObj, function (err, result) {
                if (err) reject("更新失败")
                else resolve("更新成功")
            })
        })

    },
}